axios.defaults.baseURL="http://localhost:8080";
Vue.prototype.$http=axios;


//1.axios前置拦截器：每次通过axios发送请求之前，让所有的请求都携带token
axios.interceptors.request.use(config=>{
    //从localStorage中获取token
    let token =  localStorage.getItem("token");
    //如果有值
    if(token){
        //将token设置到请求头
        config.headers['token']=token;
    }
    return config;
},error => {
    Promise.reject(error);
})

//2.axios后置拦截器：后端处理完axios请求之后，处理响应的数据
axios.interceptors.response.use(res=>{
    if (false === res.data.success && "noLogin" === res.data.msg) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        //跳转到登录页面
        location.href="login.html";
        alert("重新登录")
    }
    if (false === res.data.success && "timeout" === res.data.msg) {
        localStorage.removeItem("token");
        localStorage.removeItem("logininfo");
        alert("登录过期");
        location.href="login.html";
    }
    return res;
},error => {
    Promise.reject(error);
})


//3.静态资源拦截器：拦截不发送axios请求的页面【登录之后才能访问】
//如果访问的不是login.html 或 register.html,都要判断是否登录【logininfo】
let url = location.href; //localhost/index.html
//如果访问的不是login.html 并且 register.html,都要判断是否登录【logininfo】
if(url.indexOf("login.html")==-1
    && url.indexOf("register.html")==-1
    && url.indexOf("binder.html")==-1
    && url.indexOf("callback.html")==-1){//访问其他页面
    var logininfoStr = localStorage.getItem("logininfo");
    //如果logininfoStr没有值 - 没有登录
    if(!logininfoStr){
        //跳转到登录页面
        location.href = "login.html";
    }
}

//封装公用方法 - 将字符串的参数解析为json对象
function parseUrlParams2Obj(url) {//xxx?code=xxx&state=1
    let paramStr = url.substring(url.indexOf("?")+1);//code=xxx&state=1
    let paramArr = paramStr.split("&");//[code=xxx,state=1]
    let paramObj = {};
    for(let i = 0;i<paramArr.length;i++){
        let paramTemp = paramArr[i];//code=xxx
        let paramName = paramTemp.split("=")[0];//code
        let paramValue= paramTemp.split("=")[1];//xxx
        paramObj[paramName] = paramValue;//{code:xxx,state:1}
    }
    return paramObj;
}
